package com.study.manage.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.study.manage.dto.AjaxResponse;
import com.study.manage.dto.SessionUser;
import com.study.manage.utils.JsonMapper;

public class OrgInterceptor implements HandlerInterceptor {

    private JsonMapper jsonMapper = new JsonMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 验证用户是否登陆
        SessionUser user = (SessionUser) request.getSession().getAttribute("user");
        if (user == null) {
            if (handlerMethod.getMethod().getReturnType() == AjaxResponse.class) {
                AjaxResponse ajaxResponse = new AjaxResponse(false);
                ajaxResponse.setMsg("登陆超时或还未登陆，请刷新页面");
                response.getWriter().print(jsonMapper.toJson(ajaxResponse));
            } else {
                String strBackUrl = "http://" + request.getServerName() // 服务器地址
                        + ":" + request.getServerPort() // 端口号
                        + request.getContextPath() // 项目名称
                        + ("/".equals(request.getServletPath()) ? "/index"
                                : request.getServletPath()) // 请求页面或其他地址
                        + "%3F" + (request.getQueryString() == null ? ""
                                : request.getQueryString().replaceAll("&", "%26")); // 参数
                response.sendRedirect(request.getContextPath() + "/v2/login?retUrl=" + strBackUrl);
            }
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {}

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex) throws Exception {

    }

}
